package com.jiaai.cloud.user.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.IdWorker;

import com.jiaai.cloud.user.entity.User;
import com.jiaai.cloud.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.HashSet;

import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 佳爱网络科技
 * @since 2017-07-27
 */
@Service
public class UserService implements UserDetailsService {


    @Autowired
    private  UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        List<User> users=userMapper.selectList(new EntityWrapper().eq("loginName",s));
        if(users!=null && users.size()==1){
            Collection<SimpleGrantedAuthority> collection = new HashSet<SimpleGrantedAuthority>();
            collection.add(new SimpleGrantedAuthority(users.get(0).getRole()));
            return new org.springframework.security.core.userdetails.User(users.get(0).getLoginName(),users.get(0).getPassword(),collection);
        }

        return null;
    }

    @Transactional
    public User create(User user){
         user.setId(IdWorker.get32UUID());
         userMapper.insert(user);
         return user;
    }

    public  User getUserByNameAndRole(String userName,String roles){
          List<User> users= userMapper.selectList(new EntityWrapper().eq("loginName",userName).and("find_in_set(role,{0})",roles));
          return users!=null && users.size()>0?users.get(0):null;
    }
}
